package com.another.helper;

import java.io.File;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.util.Log;

public class UpdateReceiver extends BroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent intent) {
		try {
			String packageName = intent.getData().toString() + getApplicationName(context, intent.getData().toString(), PackageManager.GET_UNINSTALLED_PACKAGES);
			Log.d("package name", packageName);
			if(intent.getAction().equals("android.intent.action.PACKAGE_ADDED")){
				File sdcard = Environment.getExternalStorageDirectory(); 
				File file	= new File(sdcard, "Android/data/com.nusaraya.simpd/update/simpd.apk");
				file.delete();
			}
			
		} catch (Exception e) {
			Logger.e(context, "update error", "delete old file error : \n"+e.toString()); 
			e.printStackTrace();
		}
	}
	
	/**
     * This method get application name name from application package name
     */
    private String getApplicationName(Context context, String data, int flag) {

        final PackageManager pckManager = context.getPackageManager();
        ApplicationInfo applicationInformation;
        try {
            applicationInformation = pckManager.getApplicationInfo(data, flag);
        } catch (PackageManager.NameNotFoundException e) {
            applicationInformation = null;
        }
        final String applicationName = (String) (applicationInformation != null ? pckManager.getApplicationLabel(applicationInformation) : "(unknown)");

        return applicationName;
    }

}
